#include <func.h>

int main(int argc,char *argv[])
{
    int fdr=open(argv[1],O_RDONLY);//读端
    ERROR_CHECK(fdr,-1,"open");
    int fdw=open(argv[2],O_WRONLY);//写端
    ERROR_CHECK(fdw,-1,"open");
    printf("fdr=%d,fdw=%d 开始通信\n",fdr,fdw);
    char buf[1000]={0};
    fd_set readset;
    int ret;
    struct timeval t;//传入传出
    while(1)
    {
        FD_ZERO(&readset);//集合清空，纸上擦干净
        // 将标准输入和文件描述符fdr添加到readset集合中
        FD_SET(STDIN_FILENO,&readset);
        FD_SET(fdr,&readset);
        t.tv_sec=1;
        t.tv_usec=0;
        //最大描述符+1、要监控的集合（可读、可写、异常）、等待的时间
        int fd_ready_num=select(fdr+1,&readset,NULL,NULL,&t);
        if(fd_ready_num>0)
        {
            if(FD_ISSET(STDIN_FILENO,&readset))
            {
                //先读标准输入
                memset(buf,0,sizeof(buf));
                ret=read(STDIN_FILENO,buf,sizeof(buf));
                if(0==ret)
                {
                    //ctrl d
                    printf("我想结束\n");
                    break;
                }
                //发送给对方,写2号管道
                write(fdw,buf,strlen(buf)-1);
            }
            if(FD_ISSET(fdr,&readset))
            {
                memset(buf,0,sizeof(buf));
                ret=read(fdr,buf,sizeof(buf));//读管道时，管道内没有数据，会阻塞
                ERROR_CHECK(fdr,-1,"read");
                if(0==ret)
                {
                    printf("对方断开,再见\n");
                    break;
                }
                printf("%s\n",buf);
            }
        }else{
            //记录当前时间、方便调试
            time_t now=time(NULL);
            printf("超时 %s",ctime(&now));
        }
        
    }
    return 0;
}